package com.cjh.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cjh.common.dto.*;
import com.cjh.common.entity.*;
import com.cjh.common.mapper.*;
import com.cjh.common.response.Result;
import com.cjh.common.service.CommodityService;
import com.cjh.common.service.PermissionService;
import com.cjh.common.wxDto.CommodityDetailsIMSDTO;
import com.cjh.common.wxDto.CommodityDetailsValueDTO;
import com.cjh.common.wxDto.CommoditySpecificationsDTO;
import com.cjh.common.wxDto.TypeGroupDTO;
import com.cjh.common.wxDto.WXCommodityDetailsDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

/**
 *
 */
@Service
public class CommodityServiceImpl extends ServiceImpl<CommodityMapper, Commodity>
    implements CommodityService{
    @Autowired
    CommodityMapper commodityMapper;
    @Autowired
    PermissionService permissionService;
    @Autowired
    UserMapper userMapper;
    @Autowired
    CommodityDetailsMapper commodityDetailsMapper;
    @Autowired
    DetailsValueMapper detailsValueMapper;
    @Autowired
    TypeGroupMapper typeGroupMapper;
    @Override
    public Result getPagingCommodity(CommodityPagingDTO commodityPagingDTO) {
        PagingDTO<CommodityDTO> objectPagingDTO = new PagingDTO<>();
        Integer size = commodityPagingDTO.getSize();
        Integer current = commodityPagingDTO.getCurrent();
        Integer start = (current-1)*size;
        Integer storeId = commodityPagingDTO.getStoreId();
        String commodityName = commodityPagingDTO.getCommodityName();
        String username = commodityPagingDTO.getUsername();
        Integer userId = permissionService.isSuperAdministrator(username)?null:userMapper.selectOne(new QueryWrapper<User>().eq("username", username)).getUserId();
        List<CommodityDTO> allCommodity = commodityMapper.getPagingCommodity(start, size, userId, storeId, commodityName,commodityPagingDTO.getIsShow());
        objectPagingDTO.setSize(size);
        objectPagingDTO.setCurrent(current);
        objectPagingDTO.setTotal(commodityMapper.getPagingCommodityTotal(userId, storeId, commodityName,commodityPagingDTO.getIsShow()));
        objectPagingDTO.setRecords(allCommodity);
        return new Result().setCode(200).setMessage("操作成功！").setData(objectPagingDTO);
    }

    @Override
    public Result getCommodityById(Integer id) {
        return new Result().setCode(200).setMessage("操作成功！").setData(commodityMapper.getCommodityById(id));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addCommodity(AddCommodityDTO addCommodityDTO) {
        try {
            Commodity commodity = new Commodity();
            BeanUtils.copyProperties(addCommodityDTO,commodity);
            commodityMapper.insert(commodity);
            if(addCommodityDTO.getIsMultiSpecification() == 0){
                CommodityDetails commodityDetails = new CommodityDetails();
                BeanUtils.copyProperties(addCommodityDTO.getCommodityDetailsDTOList().get(0),commodityDetails);
                commodityDetails.setCommodity(commodity.getCommodity());
                commodityDetailsMapper.insert(commodityDetails);
            }else{
                for (CommodityDetailsDTO c: addCommodityDTO.getCommodityDetailsDTOList()) {
                    CommodityDetails commodityDetails = new CommodityDetails();
                    BeanUtils.copyProperties(c, commodityDetails);
                    commodityDetails.setCommodity(commodity.getCommodity());
                    commodityDetailsMapper.insert(commodityDetails);
                    DetailsValue detailsValue = new DetailsValue();
                    detailsValue.setCommodityDetailsId(commodityDetails.getCommodityDetailsId());
                    for (GroupValue d : c.getGroupValueList()) {
                        detailsValue.setGroupValueId(d.getGroupValueId());
                        detailsValueMapper.insert(detailsValue);
                    }
                }
            }
            return new Result().setCode(200).setMessage("添加成功！");
        }catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new Result().setCode(202).setMessage(e.getMessage());
        }
    }

    @Override
    public Result updateCommodity(UpdateCommodityDTO updateCommodityDTO) {
        try{
            Commodity commodity = new Commodity();
            BeanUtils.copyProperties(updateCommodityDTO,commodity);
            commodityMapper.updateById(commodity);
            for (CommodityDetails c : updateCommodityDTO.getCommodityDetailsList()){
                commodityDetailsMapper.updateById(c);
            }
            return new Result().setCode(200).setMessage("修改成功！");
        }catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new Result().setCode(202).setMessage(e.getMessage());
        }
    }

    @Override
    public Result deleteCommodity(Integer commodity) {
        try{
            Integer integer = commodityMapper.selectCommodityAllSalesByCommodity(commodity);
            if(integer >0 ){
                return new Result().setCode(201).setMessage("该商品销量不为0无法删除，只能下架！");
            }
            List<Integer> listId = commodityDetailsMapper.selectListIdByCommodity(commodity);
            detailsValueMapper.delete(Wrappers.<DetailsValue>lambdaQuery().in(DetailsValue::getCommodityDetailsId,listId));
            commodityDetailsMapper.deleteBatchIds(listId);
            commodityMapper.deleteById(commodity);
            return new Result().setCode(200).setMessage("删除成功！");
        }catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new Result().setCode(202).setMessage(e.getMessage());
        }
    }

    @Override
    public Result getAllCommodityByStoreId(Integer storeId) {
        List<WXCommodityDetailsDTO> commodity = commodityMapper.getAllCommodityByStoreId(storeId);
        return new Result().setCode(0).setMessage("获取成功!").setData(commodity);
    }

    @Override
    public Result getCommodityByCommodity(Integer commodity, Integer isMultiSpecification) {
        if( isMultiSpecification == 0){
            WXCommodityDetailsDTO commodityByCommodity = commodityMapper.getCommodityByCommodity(commodity);
            return new Result().setCode(0).setMessage("获取成功!").setData(commodityByCommodity);
        }
        CommodityDetailsIMSDTO commodityDetailsIMSDTO = new CommodityDetailsIMSDTO();

        CommoditySpecificationsDTO commodityAndSpecificationsByCommodity = commodityMapper.getCommodityAndSpecificationsByCommodity(commodity);
        commodityDetailsIMSDTO.setCommoditySpecificationsDTO(commodityAndSpecificationsByCommodity);

        List<CommodityDetailsValueDTO> commodityDetailsAndGroupValueIdListByCommodity = commodityDetailsMapper.getCommodityDetailsAndGroupValueIdListByCommodity(commodity);
        commodityDetailsIMSDTO.setCommodityDetailsValueDTOList(commodityDetailsAndGroupValueIdListByCommodity);
        commodityDetailsIMSDTO.setActiveCommodityIndex(0);

        List<TypeGroupDTO> typeGroupAndGroupValueList = typeGroupMapper.getTypeGroupAndGroupValueList(commodityAndSpecificationsByCommodity.getSpecificationsId());
        List<Integer> groupValueIdList = commodityDetailsAndGroupValueIdListByCommodity.get(0).getGroupValueIdList();
        for (TypeGroupDTO t:typeGroupAndGroupValueList) {
            for (GroupValue g : t.getGroupValueList()) {
                if (groupValueIdList.contains(g.getGroupValueId())) {
                    t.setRadioValue(g.getGroupValueId());
                    break;
                }
            }
        }
        commodityDetailsIMSDTO.setTypeGroupDTOList(typeGroupAndGroupValueList);
        return new Result().setCode(0).setMessage("获取成功!").setData(commodityDetailsIMSDTO);
    }
}




